package com.nsoft.server.service.daoImpl;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import com.nsoft.server.master.beans.UserMaster;
import com.nsoft.server.service.dao.UserDao;
import com.nsoft.thickclient.trackMove.intr.user.User;
import com.nsoft.thickclient.trackMove.intr.util.StringHelper;

public class UserDaoImpl extends
		AbstractMasterGenericJPADAO<UserMaster, Integer> implements UserDao {

	public UserMaster getbyNamePass(User user) throws NoResultException {
		Query query = getEntityManager().createQuery(
				"select user from com.nsoft.server.master.beans.UserMaster user "
						+ "where user.userCharUsername=:username and "
						+ "user.userCharPassword =:password").setParameter(
				"username", user.getLogin()).setParameter("password",
				user.getPassword());

		// UserMaster master =(UserMaster) query.getSingleResult();
		query.getResultList();
		return (UserMaster) query.getSingleResult();
	}

	public List<UserMaster> searchUsers(User user) {

		String name = "";
		StringBuffer sb = new StringBuffer();
		sb.append("select master "
				+ " from com.nsoft.server.master.beans.UserMaster"
				+ " master where 1=1 ");
		if (user.getName() != null && !user.getName().equalsIgnoreCase("")
				&& !user.getName().equalsIgnoreCase(" ")) {
			name = StringHelper.replace("*", "%", user.getName());
			sb.append("and  master.userCharUsername like '" + name + "'");
		}

		if (user.getLogin() != null && !user.getLogin().equalsIgnoreCase("")
				&& !user.getLogin().equalsIgnoreCase(" ")) {
			name = StringHelper.replace("*", "%", user.getLogin());
			sb.append("and  master.userCharUsername like '" + name + "'");
		}

		if (user.getRole() != null && !user.getRole().equalsIgnoreCase("")
				&& !user.getRole().equalsIgnoreCase(" ")) {
			name = StringHelper.replace("*", "%", user.getRole());
			sb.append("and  master.userCharRole like '" + name + "'");
		}

		Query query = getEntityManager().createQuery(sb.toString());
		return query.getResultList();
	}

}
